package com.haofengsoft.scce.controller;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.haofengsoft.scce.adapter.advert.AdvertModel;
import com.haofengsoft.scce.db.bean.AdvertInfo;
import com.haofengsoft.scce.db.biz.AdvertInfoBiz;

/**
 * Created by admin on 2015/7/14.
 */
public class AdvertController {
    private static AdvertController instance = null;
    private Context appContext;

    public static synchronized AdvertController getInstance(Context context) {
        if (instance == null) {
            instance = new AdvertController(context);
        }
        return instance;
    }

    public AdvertController(Context appContext) {
        this.appContext = appContext;
    }

    public List<AdvertModel> gainAdvertList() {
        List<AdvertInfo> infoList = AdvertInfoBiz.getInstance(appContext).gainAdvertList();
        List<AdvertModel> modelList = new ArrayList<AdvertModel>();
        for (AdvertInfo info : infoList) {
            AdvertModel model = new AdvertModel();
            model.setImageUr(info.getImageUrl());
            modelList.add(model);
        }
        return modelList;
    }

    public boolean gainBuyInfoModels(String json) {
        try {

            JSONArray parAry = JSON.parseArray(json);
            int count = parAry.size();
            List<AdvertInfo> infoList = new ArrayList<AdvertInfo>();
            for (int i = 0; i < count; i++) {
                JSONObject childObj = parAry.getJSONObject(i);
                AdvertInfo info = new AdvertInfo();
                info.setId(childObj.getString("ID"));
                info.setTitle(childObj.getString("AdvertName"));
                info.setImageUrl(childObj.getString("ImagePath"));
                info.setUrlAddr(childObj.getString("Url"));
                info.setAdvertType(childObj.getString("AdvertType"));
                info.setStatus(childObj.getIntValue("Status"));
                infoList.add(info);
            }
            AdvertInfoBiz.getInstance(appContext).insertAddressInfoList(infoList);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
